package com.lebang.service.cences;

import com.lebang.common.utils.MD5;
import com.lebang.common.validcode.ValidCodeRecordService;
import com.lebang.component.RedisClient;
import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.*;
import com.lebang.example.ActiveMemberExample;
import com.lebang.example.CencesApruExample;
import com.lebang.example.CensusExample;
import com.lebang.mapper.*;
import com.lebang.model.MyConfig;
import com.lebang.model.Whether;
import com.lebang.model.cences.CencesMsg;
import com.lebang.model.cences.CensusModel;
import com.lebang.model.cences.MemberNewTradeCount;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.model.statistics.StatisticsRecord;
import com.lebang.service.NewRouseService;
import com.lebang.service.mongodb.CencesMsgMongodb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.lebang.service.buss.MemberService.MEMBER_LOGIN_RECORD;
import static java.math.BigDecimal.ROUND_HALF_DOWN;

/**
 * @Author: hwq
 * @Date: 2019/10/9 9:32
 * @Version 1.0
 */
@Service
@Slf4j
public class CensusService {
    @Autowired
    private LbbMemberMapper lbbMemberMapper;
    @Autowired
    private LbbMemberTradeMapper tradeMapper;

    @Autowired
    private CensusMapper censusMapper;
    //@Autowired
  //  private JavaMailSender javaMailSender;
    @Autowired
    private CencesApruMapper apruMapper;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private MemberNewTradeMapper memberNewTradeMapper;
    @Autowired
    private LbbMemberRecordMapper lbbMemberRecordMapper;
    @Autowired
    private NewRouseService newRouseService;
    @Value("${info.name}")
    private String APP_NAME;
    @Autowired
    private SendEmailMapper sendEmailMapper;
    @Autowired
    private CencesMsgMongodb cencesMsgMongodb;
    @Autowired
    private MemberCashWithdrawalMapper memberCashWithdrawalMapper;
    @Autowired
    private MemberCashFastWithdrawalMapper memberCashFastWithdrawalMapper;
    @Autowired
    private ValidCodeRecordService validCodeRecordService;

    @Value("${info.manager-background}")
    public String MANAGER_BACKGROUND;

    @Autowired
    private CencesEmailDataMapper cencesEmailDataMapper;
    @Autowired
    private CencesTaskDataMapper cencesTaskDataMapper;
    @Autowired
    private ActiveMemberMapper activeMemberMapper;

    public void dayCensus(LocalDateTime end) {

        long starTime=System.currentTimeMillis();
        Census census = new Census(MyConfig.getEnv());

        LocalDateTime star = end.minusDays(1);
        String starr = star.toLocalDate().format(DateTimeFormatter.ISO_DATE).replace("-", "");
        String endd = end.toLocalDate().format(DateTimeFormatter.ISO_DATE).replace("-", "");

        //    今天新增激活用户多少
        //    今天新增注册用户多少
        int resisterMemberCount = lbbMemberMapper.resisterMemberCount(star, end);


        census.setResisterMemberCount(resisterMemberCount);
        List<CensusModel> allMoneyList=memberNewTradeMapper.allMoneyList(star,end,null);
        //转map
        Map<String, CensusModel> modelMap =allMoneyList.stream().collect(Collectors.toMap(CensusModel::getCategory, s->s));
        CensusModel censusModel=new CensusModel();
        //    今天做了新手任务以外其他任务的新用户有多少？
        int otherRecordCountNewMember = memberNewTradeMapper.countByNotCategoryGroupByMemberId(star, end, TaskCategory.NEW_HAND.name(), Whether.YES.getDbIndex(), null);
        census.setOtherRecordCountNewMember(otherRecordCountNewMember);
        //    今天只做了新手任务的新用户有多少
        int newHandCount = resisterMemberCount - otherRecordCountNewMember;
        census.setNewHandCount(newHandCount);
        //    今天做了除新手任务的用户有多少？
        int otherRecordCountMember = memberNewTradeMapper.countByNotCategoryGroupByMemberId(star, end, TaskCategory.NEW_HAND.name(), null, null);
        census.setOtherRecordCountMember(otherRecordCountMember);
        //    今天做任务的用户有多少
        int hasRecordCount = memberNewTradeMapper.countByCategoryGroupByMemberId(star, end, null, null, null);
        //    今天做了除新手任务的任务量有多少
        int recordCount = memberNewTradeMapper.countNotByCategory(star, end, TaskCategory.NEW_HAND.name(), null, null);
        census.setRecordCount(recordCount);

        census.setHasRecordCount(hasRecordCount);
        //    今天我们的自营任务收入多少
        censusModel=this.getData(modelMap, TaskCategory.Common.name(),censusModel);
        BigDecimal todayMyTaskMoney = censusModel.getMyAmount();
        census.setTodayMyTaskMoney(todayMyTaskMoney);
        //    今天用户的自营任务收入多少
        BigDecimal todayUserTaskMoney = censusModel.getAmount();
        census.setTodayUserTaskMoney(todayUserTaskMoney);

        //闲玩的SDK收入,支出
        censusModel=this.getData(modelMap, TaskCategory.XianWan.name(),censusModel);
        BigDecimal xianWanMySdkMoney =  censusModel.getMyAmount();
        BigDecimal xianwanUserSdkMoney = censusModel.getAmount();
        //91淘金的sdk收入,支出
        censusModel=this.getData(modelMap, TaskCategory.TAOJIN.name(),censusModel);
        BigDecimal taoJinMySdkMoney = censusModel.getMyAmount();
        BigDecimal taoJinUserSdkMoney =censusModel.getAmount();
        //傲天任务的sdk收入,支出
        censusModel=this.getData(modelMap, TaskCategory.AoTian.name(),censusModel);
        BigDecimal aoTianMySdkMoney = censusModel.getMyAmount();
        BigDecimal aoTianUserSdkMoney = censusModel.getAmount();
        //pc蛋蛋享玩的sdk收入,支出
        censusModel=this.getData(modelMap, TaskCategory.PCDANDAN.name(),censusModel);
        BigDecimal danDanMySdkMoney = censusModel.getMyAmount();
        BigDecimal danDanUserSdkMoney = censusModel.getAmount();
        //乐享多游的sdk收入,支出
        censusModel=this.getData(modelMap, TaskCategory.LEXIANG.name(),censusModel);
        BigDecimal leXiangMySdkMoney = censusModel.getMyAmount();
        BigDecimal leXiangUserSdkMoney = censusModel.getAmount();
        //聚享玩的sdk收入,支出
        censusModel=this.getData(modelMap, TaskCategory.JUXIANGWAN.name(),censusModel);
        BigDecimal juXiangWanMySdkMoney = censusModel.getMyAmount();
        BigDecimal juXiangWanUserSdkMoney = censusModel.getAmount();

        //鱼玩盒子的sdk收入,支出
        censusModel=this.getData(modelMap, TaskCategory.YW_HZ.name(),censusModel);
        BigDecimal yWHZMySdkMoney = censusModel.getMyAmount();
        BigDecimal YWHZUserSdkMoney = censusModel.getAmount();
        //    今天我们的SDK收入
        BigDecimal todayMySdkMoney = xianWanMySdkMoney.add(taoJinMySdkMoney)
                .add(aoTianMySdkMoney)
                .add(danDanMySdkMoney)
                .add(leXiangMySdkMoney)
                .add(juXiangWanMySdkMoney)
                .add(yWHZMySdkMoney);
        census.setTodayMySdkMoney(todayMySdkMoney);
        //    今天用户的SDK收入
        BigDecimal todayUserSdkMoney = xianwanUserSdkMoney.add(taoJinUserSdkMoney)
                .add(aoTianUserSdkMoney)
                .add(danDanUserSdkMoney)
                .add(leXiangUserSdkMoney)
                .add(juXiangWanUserSdkMoney)
                .add(YWHZUserSdkMoney);
        //新手任务支出
        censusModel=this.getData(modelMap, TaskCategory.NEW_HAND.name(),censusModel);
        BigDecimal newHandUserSdkMoney =censusModel.getAmount();
        //新闻赚支出
        censusModel=this.getData(modelMap, TaskCategory.NEWS_EARN.name(),censusModel);
        BigDecimal newsEarnUserSdkMoney =censusModel.getAmount();
        //搞笑赚支出
        censusModel=this.getData(modelMap, TaskCategory.JOKE_EARN.name(),censusModel);
        BigDecimal jokeEarnUserSdkMoney = censusModel.getAmount();
        //转盘支出
        censusModel=this.getData(modelMap, TaskCategory.ZPCJ.name(),censusModel);
        BigDecimal zpcjusersdkmoney = censusModel.getAmount();
        //看视频赚钱支出
        censusModel=this.getData(modelMap, TaskCategory.CHUANGSHANJIA.name(),censusModel);
        BigDecimal chuangShanJiaUserSdkMoney = censusModel.getAmount();


        census.setTodayUserSdkMoney(todayUserSdkMoney);
        //    今天总的营收有多少？
        BigDecimal todayAllMyMoney = (todayMyTaskMoney.subtract(todayUserTaskMoney)).add(todayMySdkMoney.subtract(todayUserSdkMoney));

        //     今天总的支出有多少
        BigDecimal todayAllUserMoney = this.all(allMoneyList);

        census.setTodayAllMyMoney(todayAllMyMoney);
        //    今天审核提现成功有多少？
        BigDecimal todayAllCashMoney = tradeMapper.todayAllCashMoney(star, end);
        if (todayAllCashMoney == null) {
            todayAllCashMoney = BigDecimal.ZERO;
        }
        BigDecimal NewTodayAllCashMoney=memberCashWithdrawalMapper.todayAllCashMoney(star,end);
        if (NewTodayAllCashMoney == null) {
            NewTodayAllCashMoney = BigDecimal.ZERO;
        }
        todayAllCashMoney=todayAllCashMoney.add(NewTodayAllCashMoney);
        census.setTodayAllCashMoney(todayAllCashMoney);
        //    今天申请提现今天审核成功有多少？
        BigDecimal todayCreatCashMoney = tradeMapper.todayCreatCashMoney(star, end);
        if (todayCreatCashMoney == null) {
            todayCreatCashMoney = BigDecimal.ZERO;
        }

        BigDecimal NewtodayCreatCashMoney = memberCashWithdrawalMapper.todayCreatCashMoney(star, end);
        if (NewtodayCreatCashMoney == null) {
            NewtodayCreatCashMoney = BigDecimal.ZERO;
        }
        todayCreatCashMoney=todayCreatCashMoney.add(NewtodayCreatCashMoney);
                census.setTodayCreatCash(todayCreatCashMoney);
        //    今天申请提现待审核有多少？
        BigDecimal todayWaitCashMoney = tradeMapper.todayWaitCashMoney(star, end);
        if (todayWaitCashMoney == null) {
            todayWaitCashMoney = BigDecimal.ZERO;
        }
        census.setTodayWaitCash(todayWaitCashMoney);
        //    今天有多少用户完成了闲玩的任务，完成了多少次任务，金额
        censusModel=this.getData(modelMap, TaskCategory.XianWan.name(),censusModel);
        int todayXianWanMember = censusModel.getCount();
        census.setTodayXianWanMember(todayXianWanMember);
        BigDecimal todayXianWanMoney = censusModel.getMyAmount();
        census.setTodayXianWanMoney(todayXianWanMoney);
        //    今天有多少用户完成了多游的任务，完成了多少次任务，金额
        censusModel=this.getData(modelMap, TaskCategory.LEXIANG.name(),censusModel);
        int todayduoyouMember = censusModel.getCount();
        census.setTodayDuoYouMember(todayduoyouMember);
        BigDecimal todayduoyouMoney = censusModel.getMyAmount();
        census.setTodayDuoYouMoney(todayduoyouMoney);
        //    今天有多少用户完成了傲天的任务，完成了多少次任务，金额
        censusModel=this.getData(modelMap, TaskCategory.AoTian.name(),censusModel);
        int todayaotianMember = censusModel.getCount();
        census.setTodayAoTianMember(todayaotianMember);
        BigDecimal todayaotianMoney = censusModel.getMyAmount();
        census.setTodayAoTianMoney(todayaotianMoney);
        //取新注册的用户
         allMoneyList=memberNewTradeMapper.allMoneyList(star,end, Whether.YES.getDbIndex());
        //转map
         modelMap =allMoneyList.stream().collect(Collectors.toMap(CensusModel::getCategory, s->s));
        //    今天注册的用户，完成闲玩的用户数，金额
        censusModel=this.getData(modelMap, TaskCategory.XianWan.name(),censusModel);
        int xianWanMember = censusModel.getCount();
        census.setXianWanMember(xianWanMember);
        BigDecimal xianwanMoney = censusModel.getMyAmount();
        census.setXianWanMoney(xianwanMoney);
        //    今天注册的用户，完成多游的用户数，金额
        censusModel=this.getData(modelMap, TaskCategory.LEXIANG.name(),censusModel);
        int duoyouMember = censusModel.getCount();
        census.setDuoYouMember(duoyouMember);
        BigDecimal duoyouMoney = censusModel.getMyAmount();
        census.setDuoYouMoney(duoyouMoney);
        //    今天注册的用户，完成傲天的用户数，金额
        censusModel=this.getData(modelMap, TaskCategory.AoTian.name(),censusModel);
        int aotianMember = censusModel.getCount();
        census.setAoTianMember(aotianMember);
        BigDecimal aotianMoney = censusModel.getMyAmount();
        if (aotianMoney == null) {
            aotianMoney = BigDecimal.ZERO;
        }
        census.setAoTianMoney(aotianMoney);


        //......
        census.setCreateTime(LocalDate.now());

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        int time = Integer.parseInt(end.toLocalDate().minusDays(1).format(df));
        census.setTime(time);

        //统计出所有设备
        CencesApru cencesApru = apruMapper.selectByAll(Integer.parseInt(starr), Integer.parseInt(endd), 1, "all",MyConfig.getEnv());
        if (null == cencesApru) {
            cencesApru = new CencesApru();
            cencesApru.setXffeMoney(BigDecimal.ZERO);
            cencesApru.setXffrsCount(0);
            cencesApru.setXfflRate(BigDecimal.ZERO);
            cencesApru.setZffeMoney(BigDecimal.ZERO);
            cencesApru.setZffrsCount(0);
            cencesApru.setZfflRate(BigDecimal.ZERO);
            cencesApru.setArppu(BigDecimal.ZERO);
            cencesApru.setArpu(BigDecimal.ZERO);
            cencesApru.setKeepMemberCount(0);
            cencesApru.setResisterMemberCount(0);
        }
        int fastCount=memberCashFastWithdrawalMapper.countByFastCash(star,end);
        BigDecimal money=memberCashFastWithdrawalMapper.sumByFastCash(star,end);
        census.setFastCount(fastCount);
        if(money==null){
            money=BigDecimal.ZERO;
        }
        census.setFastMoney(money);
        //获取所有的每日必赚
        //List<TaskRouse> rouses = newRouseService.selectAll();


        // //每日必赚 先注释掉不显示

        // //汇总新用戶签到统计
        // CencesClick newAll = cencesClickService.sumData(Integer.parseInt(starr), Integer.parseInt(endd), null, 1, 1, null);
        // //汇总老用户签到统计
        // CencesClick oldAll = cencesClickService.sumData(Integer.parseInt(starr), Integer.parseInt(endd), null, 0, 1, null);
        // //汇总新用户每日赚统计
        //  CencesEarnDay newEarnDayAll = cencesEarnDayService.sumData(Integer.parseInt(starr), Integer.parseInt(endd), null, 1, 1, null);
        //  //汇总老用户每日赚统计
        //  CencesEarnDay oldEarnDayAll = cencesEarnDayService.sumData(Integer.parseInt(starr), Integer.parseInt(endd), null, 0, 1, null);

        // 说是不显示每日必赚这一块的数据，不知道后续还要不要，先注释掉
        // StringBuffer earnDayText = new StringBuffer();
        // rouses.forEach(s -> {
        //     String sdkKey = s.getSdkKey();
        //    String taskName = s.getTaskName();
        //    Long id = s.getId();

        //     //获取新用户签到统计
        //     CencesClick cencesClickNew = cencesClickService.sumData(Integer.parseInt(starr), Integer.parseInt(endd), null, 1, 1, id.intValue());
        //获取老用户签到统计
        //     CencesClick cencesClickOld = cencesClickService.sumData(Integer.parseInt(starr), Integer.parseInt(endd), null, 0, 1, id.intValue());
        //获取新用户每日赚统计
        //     CencesEarnDay cencesEarnDayNew = cencesEarnDayService.sumData(Integer.parseInt(starr), Integer.parseInt(endd), null, 1, 1, sdkKey);
        //获取老用户每日赚统计
        //     CencesEarnDay cencesEarnDayOld = cencesEarnDayService.sumData(Integer.parseInt(starr), Integer.parseInt(endd), null, 0, 1, sdkKey);


        //     earnDayText.append(taskName).append("\n").append("新用户领取").append(null == cencesEarnDayNew ? 0 : cencesEarnDayNew.getWaitCount()).append("份/完成").append(null == cencesEarnDayNew ? 0 : cencesEarnDayNew.getSuccessCount()).append("份/支出").append(null == cencesEarnDayNew ? BigDecimal.ZERO : cencesEarnDayNew.getDownRebate().setScale(2, RoundingMode.HALF_UP)).append("元/签到支出").append(null == cencesClickNew ? BigDecimal.ZERO : cencesClickNew.getClickRebate().setScale(2, RoundingMode.HALF_UP)).append("元\n").append("老用户领取").append(null == cencesEarnDayOld ? 0 : cencesEarnDayOld.getWaitCount()).append("份/完成").append(null == cencesEarnDayOld ? 0 : cencesEarnDayOld.getSuccessCount()).append("份/支出").append(null == cencesEarnDayOld ? BigDecimal.ZERO : cencesEarnDayOld.getDownRebate().setScale(2, RoundingMode.HALF_UP)).append("元/签到支出").append(null == cencesClickOld ? BigDecimal.ZERO : cencesClickOld.getClickRebate().setScale(2, RoundingMode.HALF_UP)).append("元\n");

        // });

        // 先不显示，注释掉
        // List<RecordModel> recordModels = recordMapper.cencusTodayRecord(star, end);


        List<String> emails = sendEmailMapper.selectByEnable();
        String[] list = emails.toArray(new String[emails.size()]);

        censusMapper.insertAll(census);
        //统计昨日每日短信发送量
        Long validNumDay = validCodeRecordService.countValidNum(star, end);

        SimpleMailMessage message = null;
        try {
            message = new SimpleMailMessage();
            message.setFrom("service@gara.cc");
            message.setTo(list);
            message.setSubject(APP_NAME + star.format(df) + "--" + end.format(df) + "统计");

            //获取审核成功的统计内容
            List<StatisticsRecord> statisticsRecordList = lbbMemberRecordMapper.sumRecordByTimeSuccess(star, end,MyConfig.getEnv());
            StringBuffer innnerText = new StringBuffer();
            AtomicReference<BigDecimal> userTaskMoney = new AtomicReference<>(BigDecimal.ZERO);
            AtomicReference<BigDecimal> myTaskMoney = new AtomicReference<>(BigDecimal.ZERO);
            statisticsRecordList.forEach(statisticsRecord -> {
                userTaskMoney.set(userTaskMoney.get().add(statisticsRecord.getUserMoney()));
                myTaskMoney.set(myTaskMoney.get().add(statisticsRecord.getMyMoney()));
                //获取审核失败的数量
                Integer count = lbbMemberRecordMapper.countFaiulRecord(statisticsRecord.getTaskId(), star, end,MyConfig.getEnv());
                innnerText.append("[").append(statisticsRecord.getTitle()).append("]审核通过").append(statisticsRecord.getTotal()).append("个,审核失败").append(count).append("个,收入").append(statisticsRecord.getMyMoney()).append("元,支出").append(statisticsRecord.getUserMoney()).append("元\n");
            });

            // text.append(earnDayText);


            //            先不显示，注释掉
//            for (RecordModel next : recordModels) {
//                next.setTitle(map.get(next.getTaskId()));
//                if (!TextUtil.isEmpty(next.getTitle())) {
//                    text.append(next.getTitle()).append("          ").append(next.getSuccessCount()).append("     ").append(next.getFailCount()).append("     ").append(next.getReleaseCount()).append("     ").append(next.getRedoCount()).append("     ").append(next.getMyMoney()).append("     ").append(next.getUserMoney()).append("\n");
//                }
//            }

            String text = "一、基础数据\n" +
                    "新增用户" + cencesApru.getResisterMemberCount() + "/活跃用户" + cencesApru.getKeepMemberCount() +" 短信验证数:"+validNumDay+ "\n" +
                    "新献收人数" + cencesApru.getXffrsCount() + "/新献收额" + cencesApru.getXffeMoney().setScale(2, RoundingMode.HALF_UP) + "/新献收率" + cencesApru.getXfflRate().setScale(2, RoundingMode.HALF_UP) + "\n" +
                    "总献收人数" + cencesApru.getZffrsCount() + "/总献收额" + cencesApru.getZffeMoney().setScale(2, RoundingMode.HALF_UP) + "/总献收率" + cencesApru.getZfflRate().setScale(2, RoundingMode.HALF_UP) + "%\n" +
                    "今日总营收" + todayAllMyMoney.setScale(2, RoundingMode.HALF_UP) + "元/支出" + todayAllUserMoney.setScale(2, RoundingMode.HALF_UP) + "元/提现" + todayAllCashMoney.setScale(2, RoundingMode.HALF_UP) + "元\n" +
                    "今日申请提现今日申请成功:" + todayCreatCashMoney.setScale(2, RoundingMode.HALF_UP) + "元\n" +
                    "一元提现:" + money + "元\n" +"一元提现个数:"+fastCount+"个\n"+
                    "ARPU/ARPPU:" + cencesApru.getArpu().setScale(2, RoundingMode.HALF_UP) + "/" + cencesApru.getArppu().setScale(2, RoundingMode.HALF_UP) + "\n" + "\n" + "\n" +
                    "二、SDK完成数据\n" + "今日总收入" + todayMySdkMoney + "元,支出" + todayUserSdkMoney + "元\n" +
                    "[闲玩]收入" + (null == xianWanMySdkMoney ? BigDecimal.ZERO : xianWanMySdkMoney) + "元,支出" + (null == xianwanUserSdkMoney ? BigDecimal.ZERO : xianwanUserSdkMoney) + "元\n" +
                    "[91淘金]收入" + (null == taoJinMySdkMoney ? BigDecimal.ZERO : taoJinMySdkMoney) + "元,支出" + (null == taoJinUserSdkMoney ? BigDecimal.ZERO : taoJinUserSdkMoney) + "元\n" +
                    "[傲天任务]收入" + (null == aoTianMySdkMoney ? BigDecimal.ZERO : aoTianMySdkMoney) + "元,支出" + (null == aoTianUserSdkMoney ? BigDecimal.ZERO : aoTianUserSdkMoney) + "元\n" +
                    "[pc蛋蛋享玩]收入" + (null == danDanMySdkMoney ? BigDecimal.ZERO : danDanMySdkMoney) + "元,支出" + (null == danDanUserSdkMoney ? BigDecimal.ZERO : danDanUserSdkMoney) + "元\n" +
                    "[乐享多游]收入" + (null == leXiangMySdkMoney ? BigDecimal.ZERO : leXiangMySdkMoney) + "元,支出" + (null == leXiangUserSdkMoney ? BigDecimal.ZERO : leXiangUserSdkMoney) + "元\n" +
                    "[聚享玩]收入" + (null == juXiangWanMySdkMoney ? BigDecimal.ZERO : juXiangWanMySdkMoney) + "元,支出" + (null == juXiangWanUserSdkMoney ? BigDecimal.ZERO : juXiangWanUserSdkMoney) + "元\n"+
                    "[鱼玩盒子]收入" + (null == yWHZMySdkMoney ? BigDecimal.ZERO : yWHZMySdkMoney) + "元,支出" + (null == YWHZUserSdkMoney ? BigDecimal.ZERO : YWHZUserSdkMoney) + "元\n" + "\n" + "\n" +
                    "三、截图完成数据\n" +
                    "今日总收入" + myTaskMoney.get() + "元,支出" + userTaskMoney.get() + "元\n" +
                    innnerText +
                    "\n" + "\n" + "四、其他支出情况\n" + "[新手任务]支出" +
                    (null == newHandUserSdkMoney ? BigDecimal.ZERO : newHandUserSdkMoney.setScale(2, RoundingMode.HALF_UP)) + "元\n"
                    + "[新闻赚]支出" + (null == newsEarnUserSdkMoney ? BigDecimal.ZERO : newsEarnUserSdkMoney.setScale(2, RoundingMode.HALF_UP)) + "元\n"
                    + "[搞笑赚]支出" + (null == jokeEarnUserSdkMoney ? BigDecimal.ZERO : jokeEarnUserSdkMoney.setScale(2, RoundingMode.HALF_UP)) + "元\n"
                    + "[转盘]支出" + (null == zpcjusersdkmoney ? BigDecimal.ZERO : zpcjusersdkmoney.setScale(2, RoundingMode.HALF_UP)) + "元\n"
                    + "[看视频赚钱]支出" + (null == chuangShanJiaUserSdkMoney ? BigDecimal.ZERO : chuangShanJiaUserSdkMoney.setScale(2, RoundingMode.HALF_UP)) + "元\n"
                    + "[走路赚]支出" + (memberNewTradeMapper.selectUserMoneyByCategory(TaskCategory.WALK_EARNS.name(), star, end, null, null).toPlainString()) + "元\n"

                    + "[吃饭赚]支出" + (memberNewTradeMapper.selectUserMoneyByCategory(TaskCategory.EAT_EARNS.name(), star, end, null, null).toPlainString()) + "元\n"
                    + "[睡觉赚]支出" + (memberNewTradeMapper.selectUserMoneyByCategory(TaskCategory.SLEEP_EARNS.name(), star, end, null, null).toPlainString()) + "元\n"
                    + "[走路赚悬浮金币]支出" + (memberNewTradeMapper.selectUserMoneyByCategory(TaskCategory.POINT_EARN.name(), star, end, null, null).toPlainString()) + "元\n";
            // "\n" +
// "\n"
//    +
// "二、每日必赚完成数据\n" +
// "汇总\n" +
// "新用户领取" + (null == newEarnDayAll ? 0 : newEarnDayAll.getWaitCount()) + "份/完成" + (null == newEarnDayAll ? 0 : newEarnDayAll.getSuccessCount()) + "份/支出" + (null == newEarnDayAll ? BigDecimal.ZERO : newEarnDayAll.getDownRebate().setScale(2, RoundingMode.HALF_UP)) + "元/签到支出" + (null == newAll ? BigDecimal.ZERO : newAll.getClickRebate().setScale(2, RoundingMode.HALF_UP)) + "元\n" +
// "老用户领取" + (null == oldEarnDayAll ? 0 : oldEarnDayAll.getWaitCount()) + "份/完成" + (null == oldEarnDayAll ? 0 : oldEarnDayAll.getSuccessCount()) + "份/支出" + (null == oldEarnDayAll ? BigDecimal.ZERO : oldEarnDayAll.getDownRebate().setScale(2, RoundingMode.HALF_UP)) + "元/签到支出" + (null == oldAll ? BigDecimal.ZERO : oldAll.getClickRebate().setScale(2, RoundingMode.HALF_UP)) + "元\n"
            message.setText(text);
            //javaMailSender.send(message);
            cencesMsgMongodb.save(new CencesMsg("每日数据统计",(System.currentTimeMillis()-starTime)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private BigDecimal all(List<CensusModel> modelMap) {
        BigDecimal total=BigDecimal.ZERO;
        modelMap.forEach(s-> total.add(s.getAmount()));
        return total;
    }

    private CensusModel getData(Map<String, CensusModel> modelMap, String category, CensusModel censusModel) {
        censusModel=modelMap.get(category);
        if(censusModel==null){
            censusModel=new CensusModel();
            censusModel.setAmount(BigDecimal.ZERO);
            censusModel.setMyAmount(BigDecimal.ZERO);
            censusModel.setCount(0);
        }
        return censusModel;
    }
    @DataSource("commonDB")
    public long countByExample(CensusExample example) {
        return censusMapper.countByExample(example);
    }
    @DataSource("commonDB")
    public List<Census> selectByExample(CensusExample example) {
        return censusMapper.selectByExample(example);
    }

    /**
     * 每日arppu统计
     *
     * @param end
     */
    public void newCensus(LocalDateTime end) {
        long starTime=System.currentTimeMillis();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDateTime star = end.minusDays(1);
        int time = Integer.parseInt(end.toLocalDate().minusDays(1).format(df));
        List<CencesApru> list = apruMapper.selectBrandCount(star, end);

        //通用任务,试玩任务
        List<String> newPayList = new ArrayList<>();
        newPayList.add(TaskCategory.Common.name());
        newPayList.add(TaskCategory.AoTian.name());
        newPayList.add(TaskCategory.XianWan.name());
        newPayList.add(TaskCategory.PCDANDAN.name());
        newPayList.add(TaskCategory.TAOJIN.name());
        newPayList.add(TaskCategory.LEXIANG.name());
        newPayList.add(TaskCategory.JUXIANGWAN.name());
        newPayList.add(TaskCategory.DANDAN_ZHUAN.name());
        newPayList.add(TaskCategory.YW_HZ.name());

        //根据任务类型付费额(sdk+截图)
        List<MemberNewTradeCount> memberNewTradeMoneys  = memberNewTradeMapper.sumByDate(star, end,newPayList);
        memberNewTradeMoneys.forEach(s->{s.setIsNewMemberAppstore(s.getIsNewMember()+":"+s.getAppStore());});
        Map<String,List<MemberNewTradeCount>> memberNewTradeMap = memberNewTradeMoneys.stream().collect(Collectors.groupingBy(MemberNewTradeCount::getIsNewMemberAppstore));

        newPayList.add(TaskCategory.CSJ_ZXR.name());
        //根据任务类型统计付费人数(sdk+截图+每日必赚)
        List<MemberNewTradeCount> memberNewTradeCounts = memberNewTradeMapper.countByDate(star,end,newPayList);
        memberNewTradeCounts.forEach(s->{s.setIsNewMemberAppstore(s.getIsNewMember()+":"+s.getAppStore());});
        Map<String,List<MemberNewTradeCount>> memberNewTradeCountMap = memberNewTradeCounts.stream().collect(Collectors.groupingBy(MemberNewTradeCount::getIsNewMemberAppstore));

        //根据渠道统计新增设备
        List<MemberNewTradeCount> imeiCounts = apruMapper.selectImeiByDate(star, end);
        Map<String,List<MemberNewTradeCount>> imeiMap = imeiCounts.stream().collect(Collectors.groupingBy(MemberNewTradeCount::getAppStore));

        list.forEach(s -> {
            //新增设备数
            int xzsbs = countImei(imeiMap,s.getBrand());
            s.setResisterImeiCount(xzsbs);
            //活跃用户数
            //Long huoyue = redisClient.hlen(MEMBER_LOGIN_RECORD + time + ":" + s.getBrand());
            ActiveMemberExample activeMemberExample = new ActiveMemberExample();
            activeMemberExample.createCriteria().andCreateDateEqualTo(LocalDate.now().minusDays(1)).andAppStoreEqualTo(s.getBrand());
            Long huoyue = activeMemberMapper.countByExample(activeMemberExample);

            //新付费额(sdk+截图)
            BigDecimal xffe = sumMoneyByMap(memberNewTradeMap, Whether.YES.getDbIndex(),s.getBrand());
            //总付费额(sdk+截图)
            BigDecimal zffe = xffe.add(sumMoneyByMap(memberNewTradeMap, Whether.NO.getDbIndex(),s.getBrand()));


            // 新付费人数(sdk+截图+每日必赚)
            int xffrs = countByMap(memberNewTradeCountMap, Whether.YES.getDbIndex(),s.getBrand());
            // 总付费人数(sdk+截图+每日必赚)
            int zffrs = xffrs + countByMap(memberNewTradeCountMap, Whether.NO.getDbIndex(),s.getBrand());

            //新付费率：新付费人数/当天新注册用户数
            BigDecimal xffl = BigDecimal.ZERO;
            if (xffrs != 0 && xffe != null) {
                xffl = new BigDecimal(xffrs).divide(new BigDecimal(s.getResisterMemberCount()), 2, ROUND_HALF_DOWN);
            }
            //总付费率：总付费人数/当天活跃用户数
            BigDecimal zffl = BigDecimal.ZERO;
            if (zffrs != 0 && zffe.compareTo(BigDecimal.ZERO) > 0 && huoyue != 0) {
                zffl = new BigDecimal(zffrs).divide(new BigDecimal(huoyue), 2, ROUND_HALF_DOWN);
            }
            //arppu：总付费额/总付费人数
            BigDecimal arppu = BigDecimal.ZERO;
            if (zffrs != 0 && zffe.compareTo(BigDecimal.ZERO) > 0) {
                arppu = zffe.divide(new BigDecimal(zffrs), 2, ROUND_HALF_DOWN);
            }
            //arpu：总付费用额/活跃户
            BigDecimal arpu = BigDecimal.ZERO;
            if (huoyue != 0 && zffe.compareTo(BigDecimal.ZERO) > 0) {
                arpu = zffe.divide(new BigDecimal(huoyue), 2, ROUND_HALF_DOWN);
            }
            s.setTime(time);
            s.setCreateTime(new Date());
            s.setResisterImeiCount(xzsbs);
            s.setKeepMemberCount(huoyue.intValue());
            s.setXffrsCount(xffrs);
            s.setZffrsCount(zffrs);
            s.setXffeMoney(xffe);
            s.setZffeMoney(zffe);
            s.setXfflRate(xffl);
            s.setZfflRate(zffl);
            s.setArppu(arppu);
            s.setArpu(arpu);
            s.setType(0);
            s.setAppId(MyConfig.getEnv());
            apruMapper.insertApru(s);
        });
        CencesApru all = new CencesApru();
        all.setTime(time);
        all.setCreateTime(new Date());
        all.setResisterImeiCount(0);
        all.setKeepMemberCount(0);
        all.setXffrsCount(0);
        all.setZffrsCount(0);
        all.setXffeMoney(BigDecimal.ZERO);
        all.setZffeMoney(BigDecimal.ZERO);
        all.setXfflRate(BigDecimal.ZERO);
        all.setZfflRate(BigDecimal.ZERO);
        all.setArppu(BigDecimal.ZERO);
        all.setArpu(BigDecimal.ZERO);
        all.setResisterMemberCount(0);
        all.setBrand("all");
        all.setType(1);
        all.setAppId(MyConfig.getEnv());
        list.forEach(s -> {
            all.setResisterImeiCount(all.getResisterImeiCount() + s.getResisterImeiCount());
            all.setKeepMemberCount(all.getKeepMemberCount() + s.getKeepMemberCount());
            all.setXffrsCount(all.getXffrsCount() + s.getXffrsCount());
            all.setZffrsCount(all.getZffrsCount() + s.getZffrsCount());
            all.setXffeMoney(all.getXffeMoney().add(s.getXffeMoney()));
            all.setZffeMoney(all.getZffeMoney().add(s.getZffeMoney()));
            all.setResisterMemberCount(all.getResisterMemberCount() + s.getResisterMemberCount());
        });

        //补上记录表内渠道为空字符串的付费额
        BigDecimal emptyBrandMoney = sumMoneyByMap(memberNewTradeMap, Whether.YES.getDbIndex(),"");
        all.setXffeMoney(all.getXffeMoney().add(emptyBrandMoney));
        all.setZffeMoney(all.getZffeMoney().add(emptyBrandMoney).add(sumMoneyByMap(memberNewTradeMap, Whether.NO.getDbIndex(),"")));
        //补上记录表内渠道为空字符串的付费人数
        int emptyBrandCount = countByMap(memberNewTradeCountMap, Whether.YES.getDbIndex(),"");
        all.setXffrsCount(all.getXffrsCount()+emptyBrandCount);
        all.setZffrsCount(all.getZffrsCount()+emptyBrandCount+countByMap(memberNewTradeCountMap, Whether.NO.getDbIndex(),""));

        try {

            all.setXfflRate(new BigDecimal(all.getXffrsCount()).divide(new BigDecimal(all.getResisterMemberCount()), 2, ROUND_HALF_DOWN));
            all.setZfflRate(new BigDecimal(all.getZffrsCount()).divide(new BigDecimal(all.getKeepMemberCount()), 2, ROUND_HALF_DOWN));
            all.setArppu(all.getZffeMoney().divide(new BigDecimal(all.getZffrsCount()), 2, ROUND_HALF_DOWN));
            all.setArpu(all.getZffeMoney().divide(new BigDecimal(all.getKeepMemberCount()), 2, ROUND_HALF_DOWN));
        } catch (Exception e) {

        }

        apruMapper.insertApru(all);
        cencesMsgMongodb.save(new CencesMsg("每日arppu统计",(System.currentTimeMillis()-starTime)));
    }



    @DataSource("commonDB")
    public Long countApruByExample(CencesApruExample example) {
        return apruMapper.countByExample(example);
    }

    @DataSource("commonDB")
    public List<CencesApru> selectApruByExample(CencesApruExample example) {
        return apruMapper.selectByExample(example);
    }

    @DataSource("commonDB")
    public int deldayCensus(Integer id) {
        int time=censusMapper.selectByPrimaryKey(id).getTime();
        CensusExample censusExample=new CensusExample();
        censusExample.createCriteria().andTimeEqualTo(time).andAppIdEqualTo(MyConfig.getEnv());
        return censusMapper.deleteByExample(censusExample);
    }

    /**
     * 统计任务收入
     * @param memberNewTradeMap 统计数据
     * @param isNewMember 新老用户
     * @param appStore 渠道
     * @return 返回内容
     */
    private BigDecimal sumMoneyByMap(Map<String, List<MemberNewTradeCount>> memberNewTradeMap, Integer isNewMember, String appStore) {
        BigDecimal sumMoney = BigDecimal.ZERO;
        List<MemberNewTradeCount> memberNewTradeCounts = memberNewTradeMap.get(isNewMember+":"+appStore);
        if(null==memberNewTradeCounts){
            return sumMoney;
        }
        for(MemberNewTradeCount memberNewTradeCount:memberNewTradeCounts){
            sumMoney=sumMoney.add(memberNewTradeCount.getMoney());
        }
        return sumMoney;
    }

    /**
     * 统计付费人数
     * @param memberNewTradeCountMap 统计数
     * @param isNewMember 新老用户
     * @param appStore  渠道
     * @return 返回内容
     */
    private int countByMap(Map<String, List<MemberNewTradeCount>> memberNewTradeCountMap, Integer isNewMember, String appStore) {
        AtomicInteger a=new AtomicInteger(0);
        List<MemberNewTradeCount> memberNewTradeCounts= memberNewTradeCountMap.get(isNewMember+":"+appStore);
        if(null==memberNewTradeCounts){
            return a.get();
        }
        memberNewTradeCounts.forEach(s->{
            a.addAndGet(s.getCount());
        });
        return a.get();
    }

    /**
     * 统计新增设备
     * @param imeiMap 新增设备
     * @param appStore 渠道
     * @return 返回内容
     */
    private int countImei(Map<String, List<MemberNewTradeCount>> imeiMap, String appStore) {
        AtomicInteger a=new AtomicInteger(0);
        List<MemberNewTradeCount> imeiCounts= imeiMap.get(appStore);
        if(null==imeiCounts){
            return a.get();
        }
        imeiCounts.forEach(s->{
            a.addAndGet(s.getCount());
        });
        return a.get();
    }




    /**
     * 发送后台查看地址
     */
    public void sendEmail(LocalDateTime end) {

        List<String> emails = sendEmailMapper.selectByEnable();
        String[] list = emails.toArray(new String[0]);
        LocalDateTime star = end.minusDays(1);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        int time = Integer.parseInt(end.toLocalDate().minusDays(1).format(df));
        SimpleMailMessage message = null;

        message = new SimpleMailMessage();
        message.setFrom("service@gara.cc");
        message.setTo(list);
        message.setSubject(star.format(df) + "--" + end.format(df) + "统计");
       // time=20201012;
        String tok = time+"MANAGER_BACKGROUND_LEBANG";
        String emailUrl = MANAGER_BACKGROUND+"cencesemaildata_page?time="+time+"&token="+MD5.getMD5Code(tok);

        //单独发邮件
        message.setTo(list);
        message.setSubject("全部应用"+star.format(df) + "--" + end.format(df) + "统计");

         CencesEmailData  emailData = cencesEmailDataMapper.sumByTime(time);
         List<CencesTaskData> cencesTaskDataList = cencesTaskDataMapper.sumGroubyTask(time);


        StringBuffer innnerText = new StringBuffer();
        cencesTaskDataList.forEach(statisticsRecord -> {
            innnerText.append("[").append(statisticsRecord.getTaskName()).append("]审核通过").append(statisticsRecord.getCheckSuccessNum()).append("个,审核失败").append(statisticsRecord.getCheckFailNum()).append("个,收入").append(statisticsRecord.getIncome().toPlainString()).append("元,支出").append(statisticsRecord.getExpend().toPlainString()).append("元\n");
        });


        String text = "一、基础数据\n" +
                "新增用户" + emailData.getBaseRegisterUser() + "/活跃用户" + emailData.getBaseActive() +" 短信验证数:"+emailData.getBaseMsgValid()+ "\n" +
                "有效用户数" + emailData.getBaseEffectUser() + "\n" +
                "有效活跃用户数" + emailData.getBaseEffectActive() + "%\n" +
                "今日总营收" + emailData.getBaseTotalMoney().toPlainString() + "元/提现" + emailData.getBaseUserCash().toPlainString() + "元\n" +
                 "\n" + "\n" + "\n" +
                "二、SDK完成数据\n" + "今日总收入" + emailData.getSdkTotalMoney().toPlainString() + "元,支出" + emailData.getSdkUserTotalMoney().toPlainString() + "元\n" +
                "[闲玩]收入" + emailData.getSdkXianwan().toPlainString() + "元,支出" + emailData.getSdkUserXianwan().toPlainString() + "元\n" +
                "[91淘金]收入" + emailData.getSdkNineone().toPlainString() + "元,支出" + emailData.getSdkUserNineone().toPlainString() + "元\n" +
                "[傲天任务]收入" + emailData.getSdkAotian().toPlainString() + "元,支出" + emailData.getSdkUserAotian().toPlainString() + "元\n" +
                "[pc蛋蛋享玩]收入" + emailData.getSdkDandan().toPlainString() + "元,支出" + emailData.getSdkUserDandan().toPlainString() + "元\n" +
                "[乐享多游]收入" + emailData.getSdkDuoyou().toPlainString() + "元,支出" + emailData.getSdkUserDuoyou().toPlainString() + "元\n" +
                "[聚享玩]收入" + emailData.getSdkJuxiangwan().toPlainString() + "元,支出" + emailData.getSdkUserJuxiangwan().toPlainString() + "元\n"+
                "[鱼玩盒子]收入" + emailData.getSdkYuwan().toPlainString() + "元,支出" + emailData.getSdkUserYuwan().toPlainString() + "元\n" + "\n" + "\n" +
                "三、截图完成数据\n" +
                "今日总收入" + emailData.getCommoninMoney().toPlainString() + "元,支出" + emailData.getCommonOutMoney().toPlainString() + "元\n" +
                innnerText +
                "\n" + "\n" + "四、其他支出情况\n" + "[新手任务]支出" +
                emailData.getOtherNewHand().toPlainString() + "元\n"
                + "[新闻赚]支出" + emailData.getOtherNews().toPlainString() + "元\n"
                + "[搞笑赚]支出" + emailData.getOtherJoke().toPlainString()+ "元\n"
                + "[转盘]支出" + emailData.getOtherZhuanpan().toPlainString() + "元\n"
                + "[走路赚]支出" + emailData.getOtherWalk().toPlainString() + "元\n"

                + "[吃饭赚]支出" + emailData.getOtherEat().toPlainString() + "元\n"
                + "[睡觉赚]支出" + emailData.getOtherSleep().toPlainString() + "元\n"
                +"\n"+"\n"
                +emailUrl;
        message.setText(text);
        //javaMailSender.send(message);


    }

    public void emailData(LocalDateTime end) {
        LocalDateTime star = end.minusDays(1);
        String starr = star.toLocalDate().format(DateTimeFormatter.ISO_DATE).replace("-", "");
        String endd = end.toLocalDate().format(DateTimeFormatter.ISO_DATE).replace("-", "");

        List<CensusModel> allMoneyList=memberNewTradeMapper.allMoneyList(star,end,null);
        //转map
        Map<String,CensusModel> modelMap =allMoneyList.stream().collect(Collectors.toMap(CensusModel::getCategory, s->s));
        CensusModel censusModel=new CensusModel();

        //    今天我们的自营任务收入多少
        censusModel=this.getData(modelMap,TaskCategory.Common.name(),censusModel);
        BigDecimal todayMyTaskMoney = censusModel.getMyAmount();
        //    今天用户的自营任务收入多少
        BigDecimal todayUserTaskMoney = censusModel.getAmount();
        //闲玩的SDK收入,支出
        censusModel=this.getData(modelMap,TaskCategory.XianWan.name(),censusModel);
        BigDecimal xianWanMySdkMoney =  censusModel.getMyAmount();
        BigDecimal xianwanUserSdkMoney = censusModel.getAmount();
        //91淘金的sdk收入,支出
        censusModel=this.getData(modelMap,TaskCategory.TAOJIN.name(),censusModel);
        BigDecimal taoJinMySdkMoney = censusModel.getMyAmount();
        BigDecimal taoJinUserSdkMoney =censusModel.getAmount();
        //傲天任务的sdk收入,支出
        censusModel=this.getData(modelMap,TaskCategory.AoTian.name(),censusModel);
        BigDecimal aoTianMySdkMoney = censusModel.getMyAmount();
        BigDecimal aoTianUserSdkMoney = censusModel.getAmount();
        //pc蛋蛋享玩的sdk收入,支出
        censusModel=this.getData(modelMap,TaskCategory.PCDANDAN.name(),censusModel);
        BigDecimal danDanMySdkMoney = censusModel.getMyAmount();
        BigDecimal danDanUserSdkMoney = censusModel.getAmount();
        //乐享多游的sdk收入,支出
        censusModel=this.getData(modelMap,TaskCategory.LEXIANG.name(),censusModel);
        BigDecimal leXiangMySdkMoney = censusModel.getMyAmount();
        BigDecimal leXiangUserSdkMoney = censusModel.getAmount();
        //聚享玩的sdk收入,支出
        censusModel=this.getData(modelMap,TaskCategory.JUXIANGWAN.name(),censusModel);
        BigDecimal juXiangWanMySdkMoney = censusModel.getMyAmount();
        BigDecimal juXiangWanUserSdkMoney = censusModel.getAmount();

        //鱼玩盒子的sdk收入,支出
        censusModel=this.getData(modelMap,TaskCategory.YW_HZ.name(),censusModel);
        BigDecimal yWHZMySdkMoney = censusModel.getMyAmount();
        BigDecimal YWHZUserSdkMoney = censusModel.getAmount();
        //    今天我们的SDK收入
        BigDecimal  todayMySdkMoney = xianWanMySdkMoney.add(taoJinMySdkMoney)
                .add(aoTianMySdkMoney)
                .add(danDanMySdkMoney)
                .add(leXiangMySdkMoney)
                .add(juXiangWanMySdkMoney)
                .add(yWHZMySdkMoney);
        //    今天用户的SDK收入
        BigDecimal todayUserSdkMoney = xianwanUserSdkMoney.add(taoJinUserSdkMoney)
                .add(aoTianUserSdkMoney)
                .add(danDanUserSdkMoney)
                .add(leXiangUserSdkMoney)
                .add(juXiangWanUserSdkMoney)
                .add(YWHZUserSdkMoney);
        //新手任务支出
        censusModel=this.getData(modelMap,TaskCategory.NEW_HAND.name(),censusModel);
        BigDecimal newHandUserSdkMoney =censusModel.getAmount();
        //新闻赚支出
        censusModel=this.getData(modelMap,TaskCategory.NEWS_EARN.name(),censusModel);
        BigDecimal newsEarnUserSdkMoney =censusModel.getAmount();
        //搞笑赚支出
        censusModel=this.getData(modelMap,TaskCategory.JOKE_EARN.name(),censusModel);
        BigDecimal jokeEarnUserSdkMoney = censusModel.getAmount();
        //转盘支出
        censusModel=this.getData(modelMap,TaskCategory.ZPCJ.name(),censusModel);
        BigDecimal zpcjusersdkmoney = censusModel.getAmount();
        //    今天总的营收有多少？
        BigDecimal todayAllMyMoney = (todayMyTaskMoney.subtract(todayUserTaskMoney)).add(todayMySdkMoney.subtract(todayUserSdkMoney));

        //    今天审核提现成功有多少？
        BigDecimal todayAllCashMoney = tradeMapper.todayAllCashMoney(star, end);
        if (todayAllCashMoney == null) {
            todayAllCashMoney = BigDecimal.ZERO;
        }
        BigDecimal NewTodayAllCashMoney=memberCashWithdrawalMapper.todayAllCashMoney(star,end);
        if (NewTodayAllCashMoney == null) {
            NewTodayAllCashMoney = BigDecimal.ZERO;
        }
        todayAllCashMoney=todayAllCashMoney.add(NewTodayAllCashMoney);


        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        int time = Integer.parseInt(end.toLocalDate().minusDays(1).format(df));

        //统计出所有设备
        CencesApru cencesApru = apruMapper.selectByAll(Integer.parseInt(starr), Integer.parseInt(endd), 1, "all",MyConfig.getEnv());
        if (null == cencesApru) {
            cencesApru = new CencesApru();
            cencesApru.setXffeMoney(BigDecimal.ZERO);
            cencesApru.setXffrsCount(0);
            cencesApru.setXfflRate(BigDecimal.ZERO);
            cencesApru.setZffeMoney(BigDecimal.ZERO);
            cencesApru.setZffrsCount(0);
            cencesApru.setZfflRate(BigDecimal.ZERO);
            cencesApru.setArppu(BigDecimal.ZERO);
            cencesApru.setArpu(BigDecimal.ZERO);
            cencesApru.setKeepMemberCount(0);
            cencesApru.setResisterMemberCount(0);
        }


        //统计昨日每日短信发送量
        Long validNumDay = validCodeRecordService.countValidNum(star, end);

        try {
            //获取审核成功的统计内容
            List<StatisticsRecord> statisticsRecordList = lbbMemberRecordMapper.sumRecordByTimeSuccess(star, end,MyConfig.getEnv());
            AtomicReference<BigDecimal> userTaskMoney = new AtomicReference<>(BigDecimal.ZERO);
            AtomicReference<BigDecimal> myTaskMoney = new AtomicReference<>(BigDecimal.ZERO);


            cencesTaskDataMapper.deleteByAppIdAndTime(MyConfig.getEnv(),time);

            statisticsRecordList.forEach(statisticsRecord -> {
                userTaskMoney.set(userTaskMoney.get().add(statisticsRecord.getUserMoney()));
                myTaskMoney.set(myTaskMoney.get().add(statisticsRecord.getMyMoney()));
                //获取审核失败的数量
                Integer count = lbbMemberRecordMapper.countFaiulRecord(statisticsRecord.getTaskId(), star, end,MyConfig.getEnv());
                CencesTaskData cencesTaskData = new CencesTaskData(MyConfig.getEnv(),time,APP_NAME);
                cencesTaskData.setTaskName(statisticsRecord.getTitle());
                cencesTaskData.setCheckSuccessNum(statisticsRecord.getTotal());
                cencesTaskData.setCheckFailNum(count);
                cencesTaskData.setIncome(statisticsRecord.getMyMoney());
                cencesTaskData.setExpend(statisticsRecord.getUserMoney());
                cencesTaskDataMapper.insertTaskData(cencesTaskData);

            });

            cencesEmailDataMapper.deleteByTimeAndAppId(MyConfig.getEnv(),time);

            CencesEmailData cencesEmailData = new CencesEmailData(time,MyConfig.getEnv(),APP_NAME);
            cencesEmailData.setBaseTotalMoney(todayAllMyMoney.setScale(2, RoundingMode.HALF_UP));
            cencesEmailData.setBaseUserCash(todayAllCashMoney.setScale(2, RoundingMode.HALF_UP));
            cencesEmailData.setBaseRegisterUser(cencesApru.getResisterMemberCount());
            cencesEmailData.setBaseEffectUser(cencesApru.getXffrsCount());
            cencesEmailData.setBaseMsgValid(validNumDay);
            cencesEmailData.setBaseActive(cencesApru.getKeepMemberCount());
            cencesEmailData.setBaseEffectActive(cencesApru.getZffrsCount());
            cencesEmailData.setSdkTotalMoney(todayMySdkMoney);
            cencesEmailData.setSdkXianwan((null == xianWanMySdkMoney ? BigDecimal.ZERO : xianWanMySdkMoney));
            cencesEmailData.setSdkNineone((null == taoJinMySdkMoney ? BigDecimal.ZERO : taoJinMySdkMoney));
            cencesEmailData.setSdkAotian((null == aoTianMySdkMoney ? BigDecimal.ZERO : aoTianMySdkMoney));
            cencesEmailData.setSdkDandan((null == danDanMySdkMoney ? BigDecimal.ZERO : danDanMySdkMoney));
            cencesEmailData.setSdkJuxiangwan((null == juXiangWanMySdkMoney ? BigDecimal.ZERO : juXiangWanMySdkMoney));
            cencesEmailData.setSdkDuoyou((null == leXiangMySdkMoney ? BigDecimal.ZERO : leXiangMySdkMoney));
            cencesEmailData.setSdkYuwan((null == yWHZMySdkMoney ? BigDecimal.ZERO : yWHZMySdkMoney));
            cencesEmailData.setSdkUserTotalMoney(todayUserSdkMoney);
            cencesEmailData.setSdkUserXianwan((null == xianwanUserSdkMoney ? BigDecimal.ZERO : xianwanUserSdkMoney));
            cencesEmailData.setSdkUserNineone((null == taoJinUserSdkMoney ? BigDecimal.ZERO : taoJinUserSdkMoney));
            cencesEmailData.setSdkUserAotian((null == aoTianUserSdkMoney ? BigDecimal.ZERO : aoTianUserSdkMoney));
            cencesEmailData.setSdkUserDandan((null == danDanUserSdkMoney ? BigDecimal.ZERO : danDanUserSdkMoney));
            cencesEmailData.setSdkUserJuxiangwan((null == juXiangWanUserSdkMoney ? BigDecimal.ZERO : juXiangWanUserSdkMoney));
            cencesEmailData.setSdkUserDuoyou((null == leXiangUserSdkMoney ? BigDecimal.ZERO : leXiangUserSdkMoney));
            cencesEmailData.setSdkUserYuwan((null == YWHZUserSdkMoney ? BigDecimal.ZERO : YWHZUserSdkMoney));



            cencesEmailData.setCommoninMoney(myTaskMoney.get());
            cencesEmailData.setCommonOutMoney(userTaskMoney.get());
            cencesEmailData.setOtherNewHand((null == newHandUserSdkMoney ? BigDecimal.ZERO : newHandUserSdkMoney.setScale(2, RoundingMode.HALF_UP)));
            cencesEmailData.setOtherNews((null == newsEarnUserSdkMoney ? BigDecimal.ZERO : newsEarnUserSdkMoney.setScale(2, RoundingMode.HALF_UP)));
            cencesEmailData.setOtherJoke((null == jokeEarnUserSdkMoney ? BigDecimal.ZERO : jokeEarnUserSdkMoney.setScale(2, RoundingMode.HALF_UP)));
            cencesEmailData.setOtherZhuanpan((null == zpcjusersdkmoney ? BigDecimal.ZERO : zpcjusersdkmoney.setScale(2, RoundingMode.HALF_UP)));
            cencesEmailData.setOtherEat(memberNewTradeMapper.selectUserMoneyByCategory(TaskCategory.EAT_EARNS.name(), star, end, null, null));
            cencesEmailData.setOtherWalk(memberNewTradeMapper.selectUserMoneyByCategory(TaskCategory.WALK_EARNS.name(), star, end, null, null));
            cencesEmailData.setOtherSleep(memberNewTradeMapper.selectUserMoneyByCategory(TaskCategory.SLEEP_EARNS.name(), star, end, null, null));
            cencesEmailDataMapper.insertEmailData(cencesEmailData);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 重新统计初始统计
     * @param of
     */
    public void resetApru(LocalDateTime of) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        int time = Integer.parseInt(of.toLocalDate().minusDays(1).format(df));
        apruMapper.deleteByAppIdAndTime(MyConfig.getEnv(),time);
        newCensus(of);
    }
}
